package com.example.shiwuyouproject.ui.fragment.my.activity

import android.content.Intent
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Toast
import com.example.shiwuyouproject.R
import com.example.shiwuyouproject.base.BaseVmActivity
import com.example.shiwuyouproject.databinding.ActiivtyElegantdemeanorBinding
import com.example.shiwuyouproject.ui.fragment.my.activity.adapter.RewardsAndHonorsAdapter
import com.example.shiwuyouproject.ui.fragment.my.activity.viewmodel.ElegantDemeanorViewModel
import com.example.shiwuyouproject.ui.my.bean.PersonalInformationBean
import com.example.shiwuyouproject.utils.Auth
import com.example.shiwuyouproject.utils.GlideEngine
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.qiniu.android.common.FixedZone
import com.qiniu.android.storage.Configuration
import com.qiniu.android.storage.UploadManager
import com.yechaoa.yutilskt.ToastUtil
import com.yechaoa.yutilskt.YUtils
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * 风采展示照片
 */
class ElegantDemeanorActiivty:BaseVmActivity<ActiivtyElegantdemeanorBinding, ElegantDemeanorViewModel>() {
    override fun viewModelClass(): Class<ElegantDemeanorViewModel> = ElegantDemeanorViewModel::class.java

    override fun getViewBinding(): ActiivtyElegantdemeanorBinding {
      return ActiivtyElegantdemeanorBinding.inflate(layoutInflater)
    }
    private var myImgList:MutableList<String> = ArrayList()
    private var myImgAdapter: RewardsAndHonorsAdapter?=null
    private var addStatus=false
    private var myAdapterPosition=0
    override fun initData() {
        mViewModel.getRealNameAuthenticationData()
        mBinding.myTitle.tvRightTitle.visibility= View.GONE
        mBinding.myTitle.tvTitle.text="个人风采"
        myImgList.add("")
        myImgAdapter=RewardsAndHonorsAdapter(myImgList)
        mBinding.recycler.adapter=myImgAdapter
        myImgAdapter?.setOnItemChildClickListener { adapter, view, position ->
            if(view.id== R.id.imClose){
                myImgList.removeAt(position)
                val imgData = myImgList.filter { it != "" }
                if(imgData.size==4){
                    myImgList.add("")
                }
                myImgAdapter?.notifyDataSetChanged()
            }else if(view.id== R.id.myHeaderImg) {
                val stImg: String = adapter.getItem(position) as String
                myAdapterPosition = position
                addStatus = !stImg.isNotEmpty()
                val imgData = myImgList.filter { it != "" }
                if (imgData.size != 5 || addStatus) {
                    openCard()
                }
            }

        }


    }
    private fun openCard(){
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .maxSelectNum(1)//最大选择数量,默认9张
            .imageEngine(GlideEngine.createGlideEngine())
            .isCompress(true)//是否压缩
            .forResult(PictureConfig.CHOOSE_REQUEST)

    }
    private val TAG: String = RealNameAuthenticationActivity::class.java.getSimpleName()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调
                // 图片选择结果回调
                val selectList = PictureSelector.obtainMultipleResult(data)
                Log.e(TAG, "压缩:" + selectList[0].compressPath)
                upFile(selectList[0].compressPath)
            }
        }
    }
    var accessKey = "5Mq4K0HoqmBl_Clmc4x358zCHC2Zbwg1pltAFBOG"
    var secretKey = "nQbAllsv15ly9yMf05_jil7exdCHsXS1k4V7WR5d"
    var bucket = "uswy"
    var config: Configuration = Configuration.Builder()
        .zone(FixedZone.zone2)
        .connectTimeout(10)           // 链接超时。默认10秒
        .useHttps(true)               // 是否使用https上传域名
        .responseTimeout(60)          // 服务器响应超时。默认60秒
        .recorder(null)           // recorder分片上传时，已上传片记录器。默认null
        .build()
    private var upLoadManager: UploadManager?=null
    private var upToken: String? = null
    private  fun upFile(pathFile:String){
        upLoadManager= UploadManager(config)
        val auth: Auth = Auth.create(accessKey, secretKey)
        upToken = auth.uploadToken(bucket)
        val sdf = SimpleDateFormat("yyyyMMddHHmmss")
        val key1 = "icon_" + sdf.format(Date())
        upLoadManager?.put(pathFile, key1, upToken,
            { key, info, res -> //res包含hash、key等信息，具体字段取决于上传策略的设置
                if (info.isOK) {
                    if(addStatus){
                        myImgList.add(0,key)
                        if(myImgList.size==6){
                            myImgList.removeAt(myImgList.size-1)
                        }
                    }else{
                        myImgList[myAdapterPosition] = key
                    }
                    myImgAdapter?.notifyDataSetChanged()
                } else {
                    Toast.makeText(this@ElegantDemeanorActiivty, "图片上传失败，请检查网络连接", Toast.LENGTH_SHORT)
                        .show()
                    Looper.loop()
                }
            }, null
        )
    }

    override fun setListener() {
        mBinding.myTitle.tvBack.setOnClickListener { finish() }
        mBinding.btSava.setOnClickListener {
            YUtils.showLoading(this, "保存中...")
            val imgData:MutableList<String> = myImgList.filter { it != "" } as MutableList<String>
            mViewModel.preservationCard(imgData)
        }
    }

    override fun observe() {
        mViewModel.getPostStatus.observe(this,
            androidx.lifecycle.Observer<Boolean> {
                YUtils.hideLoading()
                if(it) {
                    ToastUtil.show("保存成功！")
                    finish()
                }else{
                    ToastUtil.show("保存失败！")
                }
            })
        mViewModel.getGenRenStatus.observe(this,  androidx.lifecycle.Observer<PersonalInformationBean>{
            if( it.images.size==5){
                myImgList.removeAt(0)
                myImgList.addAll(it.images)
            }else{
                myImgList.addAll(0,it.images)
            }
            myImgAdapter?.notifyDataSetChanged()
        })

    }
}